package gamer.servlet;

import gamer.Bean.LinkBean;
import gamer.data.DatabaseOpera;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.Objects;

public class WordLink extends HttpServlet {
    HashMap<String, String> idiom, now;

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        LinkBean wordLink = (LinkBean) req.getSession().getAttribute("wordLink");
        if (wordLink == null) {
            wordLink = new LinkBean();
            req.setAttribute("wordLink", wordLink);
        }
        DatabaseOpera dbs = new DatabaseOpera();
        idiom = dbs.mysqlQuery("*", "idiom", "idiom='" + req.getParameter("idiom") + "';");
        if (!idiom.isEmpty()) {
            if (wordLink.getIdiomLink().isEmpty() || Objects.equals(idiom.get("idiom").charAt(0), wordLink.getIdiomLink().getLast().get("idiom").charAt(idiom.get("idiom").length() - 1))) {
                wordLink.setIdiomLink(idiom);
                idiom=dbs.mysqlQuery("*", "idiom", "idiom like '" + idiom.get("idiom").charAt(idiom.get("idiom").length()-1) + "%';");
                if(idiom.isEmpty()) System.out.println("玩家获胜");
                else wordLink.setIdiomLink(idiom);
            } else System.out.println("接龙失败");
        } else System.out.println("成语不存在");
        req.getRequestDispatcher("jsp/game/wordLink.jsp").forward(req, resp);
    }
}